package com.jucai.pppeiyouclient.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Selection;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.bean.SkillBean;
import com.jucai.pppeiyouclient.bean.SystemRecommendBean;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.TextCheckUtils;
import com.jucai.pppeiyouclient.utils.TimeUtil;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.dialog.MessageShowDialog;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class OrderSettingActivity extends BaseActivity {
    private static final String TAG = "OrderSettingActivity : ";
    private static final int SERVICE_CITY = 1001;

    private ImageView setSwitch;
    private TextView setSysRecommend, setByHour, setByCount;
    private TextView setServiceCity, setStartOrder, setEndOrder;
    private TextView setWithCar, setWithCamera, setSubmit, setPriceUnit;
    private EditText setPrice;

    private LinearLayout setVisible;

    private TimePickerView startTimePicker, endTimePicker;
    private MessageShowDialog messageShowDialog;
    private TextView messageShowTitle, messageShowContent;
    private SystemRecommendBean recommend;

    private boolean isOpen, priceType, withCar, withCamera;
    private String price, serviceCityId, serviceCityName, start_time, end_time;
    private long start_time_stamp, end_time_stamp;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_setting);

        ((TextView) findViewById(R.id.common_title_text_main)).setText("接单设置");
        findViewById(R.id.common_title_find).setVisibility(View.INVISIBLE);

        setSwitch = (ImageView) findViewById(R.id.set_switch);
        setSysRecommend = (TextView) findViewById(R.id.set_system_recommend);
        setByHour = (TextView) findViewById(R.id.set_by_hour);
        setByCount = (TextView) findViewById(R.id.set_by_count);
        setServiceCity = (TextView) findViewById(R.id.set_service_city);
        setStartOrder = (TextView) findViewById(R.id.set_start_order);
        setEndOrder = (TextView) findViewById(R.id.set_end_order);
        setWithCar = (TextView) findViewById(R.id.set_with_car);
        setWithCamera = (TextView) findViewById(R.id.set_with_camera);
        setSubmit = (TextView) findViewById(R.id.set_submit);
        setPriceUnit = (TextView) findViewById(R.id.set_price_unit);
        setPrice = (EditText) findViewById(R.id.set_price);

        setVisible = (LinearLayout) findViewById(R.id.set_visible);

        messageShowDialog = new MessageShowDialog(OrderSettingActivity.this);
        messageShowTitle = (TextView) messageShowDialog.findViewById(R.id.message_dialog_title);
        messageShowContent = (TextView) messageShowDialog.findViewById(R.id.message_dialog_content);
    }

    @Override
    protected void initData() throws ParseException {

        ((TextView) findViewById(R.id.common_title_me)).setTextColor(Color.parseColor("#efb336"));

        setPrice.setSingleLine();

        price = getIntent().getStringExtra("price");

        isOpen = getIntent().getIntExtra("is_open", 0) == 0 ? false : true;
        withCar = getIntent().getIntExtra("with_car", 0) == 0 ? false : true;
        priceType = getIntent().getIntExtra("price_type", 0) == 0 ? false : true;
        withCamera = getIntent().getIntExtra("with_camera", 0) == 0 ? false : true;

        end_time = getIntent().getStringExtra("end_time");
        start_time = getIntent().getStringExtra("start_time");
        end_time_stamp = getIntent().getLongExtra("end_time_stamp", 0);
        start_time_stamp = getIntent().getLongExtra("start_time_stamp", 0);
        serviceCityId = getIntent().getStringExtra("service_city_id");
        serviceCityName = getIntent().getStringExtra("service_city");

        if (!TextUtils.isEmpty(start_time) && start_time.contains(":")) {
            start_time = start_time.substring(0, start_time.lastIndexOf(":"));
        }

        if (!TextUtils.isEmpty(end_time) && end_time.contains(":")) {
            end_time = end_time.substring(0, end_time.lastIndexOf(":"));
        }

        LogUtils.d(price + "|" + end_time + "|" + start_time + "|" + end_time_stamp + "|" + start_time_stamp);

        if (isOpen) {
            setVisible.setVisibility(View.VISIBLE);
            setSwitch.setImageResource(R.drawable.order_status_open);
        } else {
            setVisible.setVisibility(View.GONE);
            setSwitch.setImageResource(R.drawable.order_status_close);
        }

        if (withCar) {
            setWithCar.setBackgroundResource(R.drawable.shape_circle_orange);
        } else {
            setWithCar.setBackgroundResource(R.drawable.shape_circle_gray);
        }

        if (withCamera) {
            setWithCamera.setBackgroundResource(R.drawable.shape_circle_orange);
        } else {
            setWithCamera.setBackgroundResource(R.drawable.shape_circle_gray);
        }

        if (priceType) {
            setByCount.setBackgroundResource(R.drawable.shape_right_half_circle_orange);
            setByHour.setBackgroundResource(R.drawable.shape_left_half_circle_gray);
            setPriceUnit.setText("元/次");
        } else {
            setByCount.setBackgroundResource(R.drawable.shape_right_half_circle_gray);
            setByHour.setBackgroundResource(R.drawable.shape_left_half_circle_orange);
            setPriceUnit.setText("元/小时");
        }

        //收费
        if (price.contains(".")) {
            price = price.substring(0, price.indexOf("."));
        }
        if (TextUtils.equals(price,"0")) {
            price = "30";
        }
        setPrice.setText(price);

        //服务城市
        if (TextCheckUtils.isEmpty(serviceCityName)) {
            setServiceCity.setText("北京市");
            serviceCityId = "36";
        } else {
            setServiceCity.setText(serviceCityName);
        }

        //时间处理
        Calendar selectedDate = Calendar.getInstance();
        selectedDate.setTime(new Date());

        Calendar startDate = Calendar.getInstance();
        startDate.set(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONTH), selectedDate.get(Calendar.DATE), selectedDate.get(Calendar.HOUR_OF_DAY), selectedDate.get(Calendar.MINUTE));

        Calendar endDate = Calendar.getInstance();
        endDate.set(selectedDate.get(Calendar.YEAR) + 20, selectedDate.get(Calendar.MONTH) + 20, selectedDate.get(Calendar.DATE) + 20, selectedDate.get(Calendar.HOUR_OF_DAY) + 20, selectedDate.get(Calendar.MINUTE) + 20);

        startTimePicker = new TimePickerView.Builder(OrderSettingActivity.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                start_time_stamp = date.getTime() / 1000;
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String dateString = formatter.format(date);
                setStartOrder.setText(dateString);
                LogUtils.d(start_time_stamp + "");
            }
        }).isDialog(true).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN).setRangDate(startDate, endDate).build();

        endTimePicker = new TimePickerView.Builder(OrderSettingActivity.this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                end_time_stamp = date.getTime() / 1000;
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String dateString = formatter.format(date);
                setEndOrder.setText(dateString);
                LogUtils.d(end_time_stamp + "");
            }
        }).isDialog(true).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN).setRangDate(startDate, endDate).build();

        endTimePicker.setDate(Calendar.getInstance());
        startTimePicker.setDate(Calendar.getInstance());
        Selection.setSelection(setPrice.getText(), setPrice.getText().length());

        //第一次进来
        if (start_time_stamp == 0 && end_time_stamp == 0) {

            String timeAll = TimeUtil.getAll();
            timeAll = timeAll.substring(0, timeAll.lastIndexOf(":"));
            setStartOrder.setText(timeAll);
            setEndOrder.setText("一直在线");
            start_time_stamp = System.currentTimeMillis() / 1000;
            end_time_stamp = System.currentTimeMillis() / 1000 + 31536000 * 2;

        } else {

            setStartOrder.setText(start_time);

            if ((end_time_stamp - start_time_stamp) > 31536000) {
                setEndOrder.setText("一直在线");
            } else {
                setEndOrder.setText(end_time);
            }

        }

    }

    @Override
    protected void loadNetData() {

    }

    @Override
    protected void setListener() {

        findViewById(R.id.common_title_me).setOnClickListener(this);

        setSwitch.setOnClickListener(this);
        setSysRecommend.setOnClickListener(this);
        setByHour.setOnClickListener(this);
        setByCount.setOnClickListener(this);
        setServiceCity.setOnClickListener(this);
        setStartOrder.setOnClickListener(this);
        setEndOrder.setOnClickListener(this);
        setWithCar.setOnClickListener(this);
        setWithCamera.setOnClickListener(this);
        setSubmit.setOnClickListener(this);
        messageShowDialog.setOnclickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SERVICE_CITY:
                    serviceCityName = data.getStringExtra("city_name");

                    LogUtils.e(TAG + "select city = " + data.getStringExtra("city_name"));
                    setServiceCity.setText(serviceCityName);

                    LogUtils.e(TAG + "city show = " + setServiceCity.getText().toString());
                    serviceCityId = data.getStringExtra("city_id");
                    break;
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_me:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.set_switch:
                isOpen = !isOpen;
                if (isOpen) {
                    setVisible.setVisibility(View.VISIBLE);
                    setSwitch.setImageResource(R.drawable.order_status_open);
                    //isOpenState();
                } else {
                    new AlertDialog
                            .Builder(this)
                            .setTitle("确认您的选择")
                            .setMessage("是否确认暂停接单")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    setVisible.setVisibility(View.GONE);
                                    setSwitch.setImageResource(R.drawable.order_status_close);
                                    isOpenState();
                                }
                            })
                            .show();
                }
                break;
            case R.id.set_system_recommend:
                HashMap<String, String> param = new HashMap<>();
                param.put("service", "Accompany_Info.getRecommendPrice");
                param.put("accompany_id", SharedPreferencesUtil.getStringPreference(OrderSettingActivity.this, "PREFERENCE", "accompany_id", ""));
                param.put("token", LoginUtils.getToken(this));
                param.put("member_id",LoginUtils.getMember_id(this));
                LogUtils.e("system recommend param = " + param.toString());
                CommonRequestNetData.getJsonObjectData(OrderSettingActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
                    @Override
                    public void parseJsonObject(JSONObject jsonObject) {
                        try {
                            LogUtils.e(TAG + "jsObj = " + jsonObject.toString());
                            recommend = new Gson().fromJson(jsonObject.toString(), SystemRecommendBean.class);
                            final List<SkillBean> skills = recommend.getAccompany_skill_amount_detail();
                            final String amount = Float.parseFloat(recommend.getAccompany_skill_amount()) + "";

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                /*
                                if (skills.isEmpty() && skills != null) {
                                    messageShowTitle.setText("系统推荐价格");
                                    messageShowContent.setText("您目前未认证技能" + "\n" + "认证技能后将获得更高的推荐价格！");
                                    messageShowDialog.show();
                                }
                                */
                                    String temp = amount;
                                    if (temp.contains(".")) {
                                        temp = temp.substring(0, temp.indexOf("."));
                                    }
                                    /*if (TextUtils.equals(temp,"0")) {
                                        temp = "30";
                                    } else {
                                        temp = Integer.parseInt(temp) + 30 + "";
                                    }*/
                                    setPrice.setText(temp);
                                    if (priceType) {
                                        priceType = !priceType;
                                        LogUtils.e(TAG + "isCountChoose = " + priceType);
                                        setByCount.setBackgroundResource(R.drawable.shape_right_half_circle_gray);
                                        setByHour.setBackgroundResource(R.drawable.shape_left_half_circle_orange);
                                        setPriceUnit.setText("元/小时");
                                    }
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
                break;
            case R.id.set_by_hour:
            case R.id.set_by_count:
                priceType = !priceType;
                LogUtils.e(TAG + "isCountChoose = " + priceType);
                if (priceType) {
                    setByCount.setBackgroundResource(R.drawable.shape_right_half_circle_orange);
                    setByHour.setBackgroundResource(R.drawable.shape_left_half_circle_gray);
                    setPriceUnit.setText("元/次");
                } else {
                    setByCount.setBackgroundResource(R.drawable.shape_right_half_circle_gray);
                    setByHour.setBackgroundResource(R.drawable.shape_left_half_circle_orange);
                    setPriceUnit.setText("元/小时");
                }
                break;

            case R.id.set_service_city:
                startActivityForResult(new Intent(OrderSettingActivity.this, CitySelectActivity.class), SERVICE_CITY);
                break;

            case R.id.set_start_order:
                startTimePicker.show();
                break;

            case R.id.set_end_order:
                endTimePicker.show();
                break;

            case R.id.set_with_car:
                withCar = !withCar;
                LogUtils.e(TAG + "withCar = " + withCar);
                if (withCar) {
                    setWithCar.setBackgroundResource(R.drawable.shape_circle_orange);
                } else {
                    setWithCar.setBackgroundResource(R.drawable.shape_circle_gray);
                }
                break;

            case R.id.set_with_camera:
                withCamera = !withCamera;
                LogUtils.e(TAG + "withCamera = " + withCamera);
                if (withCamera) {
                    setWithCamera.setBackgroundResource(R.drawable.shape_circle_orange);
                } else {
                    setWithCamera.setBackgroundResource(R.drawable.shape_circle_gray);
                }
                break;

            case R.id.set_submit:
                if (!judgeEmpty().equals("")) {
                    ToastUtils.showToast(judgeEmpty());
                } else {
                    submitChangeInfo();
                }
                break;
            default:
                break;
        }
    }

    private void submitChangeInfo() {

        String acceptState = isOpen ? "1" : "0";
        String carState = withCar ? "1" : "0";
        String cameraState = withCamera ? "1" : "0";
        String priceTypeStr = priceType ? "1" : "0";

        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Info.updateAccompanyInfo");
        param.put("accompany_accept_state", acceptState);

        if (serviceCityId != null) {
            param.put("accompany_server_city", serviceCityId);
        } else {
            param.put("accompany_server_city", getIntent().getIntExtra("service_city_id", 1) + "");
        }

        param.put("accompany_accept_start_time", start_time_stamp + "");
        param.put("accompany_accept_end_time", end_time_stamp + "");

        param.put("accompany_car_state", carState);
        param.put("accompany_photograph_state", cameraState);

        param.put("accompany_price", setPrice.getText().toString());
        param.put("accompany_price_type", priceTypeStr);

        LogUtils.e(TAG + "param = " + param.toString());

        CommonRequestNetData.getJsonStringData(OrderSettingActivity.this, param, true, new CommonRequestNetData.JsonStringCallBack() {
            @Override
            public void parseJsonString(String str) {
                LogUtils.e(TAG + "str = " + str);
                ToastUtils.showToast(str);
                ActivityCollector.removeActivity(OrderSettingActivity.this);
            }
        });
    }

    private void isOpenState() {
        String acceptState = isOpen ? "1" : "0";

        HashMap<String, String> param = new HashMap<>();
        param.put("service", "Accompany_Info.updateAccompanyInfo");
        param.put("accompany_accept_state", acceptState);
        LogUtils.e(TAG + "param = " + param.toString());
        CommonRequestNetData.getJsonStringData(OrderSettingActivity.this, param, true, new CommonRequestNetData.JsonStringCallBack() {
            @Override
            public void parseJsonString(String str) {
                LogUtils.e(TAG + "str = " + str);
            }
        });
    }

    private String judgeEmpty() {
        if (setPrice.getText().toString().equals("")) {
            return "收费价格不能为空";
        }
        if (!setEndOrder.getText().toString().equals("一直在线")) {
            if (start_time_stamp > end_time_stamp) {
                return "开始时间不能大于结束时间";
            }
        }
        return "";
    }
}
